/******************************************************************************
@file:  ProdDescription.java
@author Ramesh Anandhan

DESCRIPTION
-----------------------------------------------------------------------------
Copyright (c) 2011, GEEKWAVE SOLUTIONS INC.

All rights reserved.
******************************************************************************/
package com.smartc.trading;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.smartc.connection.HttpConnection;
import com.smartc.connection.ParsedLoginData;
import com.smartc.ui.*;

public class ProdDescription extends Activity implements OnClickListener {

	private final String TAG = "ProdDescription";
	private final int DIALOG_BID = 0;
	private final int DIALOG_ERROR = 1;
	private final int DIALOG_STATUS = 2;
	private final int PROGRESS_DLG = 0x03;
	private final int TIMEUPDATE = 1;
	private final int DELAY = 60000;
	private TextView mProdName;
	private TextView mProdDesc;
	private TextView mProdPrice;
	private TextView mProdBidPrice;
	private TextView mProdTime;
	private TextView mProdSellerName;
	private TextView mProdSellerEmail;
	private TextView mBidAmount;

	private boolean mIsBiddable = true;

	private Button mBtnBid;

	private HttpConnection mCityConnection;
	private ResponseHandler mResponse = new ResponseHandler();

	private String mBidPrice = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.items_details);

		Intent intent = getIntent();
		String productId = intent.getStringExtra("idTradeProduct");
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onCreate() productId:" + productId);

		String domain = getResources().getString(R.string.domain);
		String query = getResources().getString(R.string.url_prod_details);
		String url = domain + query;
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onCreate url:" + url);
		// ParsedLoginData.mIdUser = "1";//TO_DO
		mCityConnection = new HttpConnection();
		mCityConnection.setUrl(url);
		mCityConnection.clearParam();
		mCityConnection.AddParam("idTradeProduct", productId);
		mCityConnection.AddHandler(mResponse);
		mCityConnection.Execute();

		mProdName = (TextView) findViewById(R.id.prod_Name);
		mProdDesc = (TextView) findViewById(R.id.prod_Desc);
		mProdPrice = (TextView) findViewById(R.id.prod_price);
		mProdBidPrice = (TextView) findViewById(R.id.prod_bid_price);
		mProdTime = (TextView) findViewById(R.id.prod_time);
		mProdSellerName = (TextView) findViewById(R.id.prod_seller_name);
		mProdSellerEmail = (TextView) findViewById(R.id.prod_seller_email);

		mBtnBid = (Button) findViewById(R.id.trade_btn_bid);
		mBtnBid.setOnClickListener(this);
	}

	public class ResponseHandler extends DefaultHandler {

		//private boolean TradeProducts = false;
		//private boolean Products = false;
		private boolean nmTradeProduct = false;
		private boolean nrTradeProductPrice = false;
		private boolean dtTradeStart = false;
		private boolean nrMaxHour = false;
		private boolean nrTradeHighPrice = false;
		private boolean txtTradeProduct = false;
		private boolean nmFullname = false;
		private boolean idEmail = false;
		private boolean idTradeProduct = false;

		//private boolean Messages = false;
		private boolean status = false;
		private boolean message = false;

		public String mItemName = null;
		public String mItemTime = null;
		public String mItemPrice = null;
		public String mBidPrice = null;
		public String mBidStartTime = null;
		public String mItemDesc = null;
		public String mItemSellerName = null;
		public String mItemSellerEmail = null;
		public String midTradeProduct = null;
		public String mStatus = null;
		public String mMessage = null;

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			if (this.nmTradeProduct) {
				mItemName = new String(ch, start, length);
			} else if (this.nrTradeProductPrice) {
				mItemPrice = new String(ch, start, length);
			} else if (this.nrMaxHour) {
				mItemTime = new String(ch, start, length);
			} else if (this.dtTradeStart) {
				mBidStartTime = new String(ch, start, length);
			} else if (this.nrTradeHighPrice) {
				mBidPrice = new String(ch, start, length);
			} else if (this.txtTradeProduct) {
				mItemDesc = new String(ch, start, length);
			} else if (this.nmFullname) {
				mItemSellerName = new String(ch, start, length);
			} else if (this.idEmail) {
				mItemSellerEmail = new String(ch, start, length);
			} else if (this.idTradeProduct) {
				midTradeProduct = new String(ch, start, length);
			} else if (this.status) {
				mStatus = new String(ch, start, length);
			} else if (this.message) {
				mMessage = new String(ch, start, length);
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			if (localName.equals("TradeProducts")) {
				//this.TradeProducts = false;
				Message myMessage = new Message();
				myMessage.obj = "PRODUCT";
				handler.sendMessage(myMessage);
			} else if (localName.equals("Products")) {
				//this.Products = false;
			} else if (localName.equals("nmTradeProduct")) {
				this.nmTradeProduct = false;
			} else if (localName.equals("nrTradeProductPrice")) {
				this.nrTradeProductPrice = false;
			} else if (localName.equals("nrMaxHour")) {
				this.nrMaxHour = false;
			} else if (localName.equals("dtTradeStart")) {
				this.dtTradeStart = false;
			} else if (localName.equals("nrTradeHighPrice")) {
				this.nrTradeHighPrice = false;
			} else if (localName.equals("txtTradeProduct")) {
				this.txtTradeProduct = false;
			} else if (localName.equals("nmFullname")) {
				this.nmFullname = false;
			} else if (localName.equals("idEmail")) {
				this.idEmail = false;
			} else if (localName.equals("idTradeProduct")) {
				this.idTradeProduct = false;
			} else if (localName.equals("Messages")) {
				//this.Messages = false;
				Message myMessage = new Message();
				myMessage.obj = "STATUS";
				handler.sendMessage(myMessage);
			} else if (localName.equals("status")) {
				this.status = false;
			} else if (localName.equals("message")) {
				this.message = false;
			}
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (localName.equals("TradeProducts")) {
				//this.TradeProducts = true;
			} else if (localName.equals("Products")) {
				//this.Products = true;
			} else if (localName.equals("nmTradeProduct")) {
				this.nmTradeProduct = true;
			} else if (localName.equals("nrTradeProductPrice")) {
				this.nrTradeProductPrice = true;
			} else if (localName.equals("nrMaxHour")) {
				this.nrMaxHour = true;
			} else if (localName.equals("dtTradeStart")) {
				this.dtTradeStart = true;
			} else if (localName.equals("nrTradeHighPrice")) {
				this.nrTradeHighPrice = true;
			} else if (localName.equals("txtTradeProduct")) {
				this.txtTradeProduct = true;
			} else if (localName.equals("nmFullname")) {
				this.nmFullname = true;
			} else if (localName.equals("idEmail")) {
				this.idEmail = true;
			} else if (localName.equals("idTradeProduct")) {
				this.idTradeProduct = true;
			} else if (localName.equals("Messages")) {
				//this.Messages = true;
			} else if (localName.equals("status")) {
				this.status = true;
			} else if (localName.equals("message")) {
				this.message = true;
			}

		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage msg:" + (String) msg.obj);
			String loginmsg = (String) msg.obj;
			if (loginmsg != null && loginmsg.equals("PRODUCT")) {
				// removeDialog(PROGRESS_DLG);
				if (AccountLogin.DEBUG)
					Log.i(TAG, "handleMessage mBidStartTime:"
							+ mResponse.mBidStartTime);
				String ItemTime = CalculateElapsedTime();

				mProdName.setText(mResponse.mItemName);
				mProdDesc.setText(mResponse.mItemDesc);
				mProdPrice.setText(mResponse.mItemPrice);
				mProdBidPrice.setText(mResponse.mBidPrice);
				mProdTime.setText(ItemTime);
				mProdSellerName.setText(mResponse.mItemSellerName);
				mProdSellerEmail.setText(mResponse.mItemSellerEmail);
			} else if (loginmsg != null && loginmsg.equals("STATUS")) {
				removeDialog(PROGRESS_DLG);
				showDialog(DIALOG_STATUS);
				if (mResponse.mStatus.equals("Success")) {
					mProdBidPrice.setText(mBidPrice);
				}
			}

			if (msg.what == TIMEUPDATE) {
				String ItemTime = CalculateElapsedTime();
				mProdTime.setText(ItemTime);
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		if (mIsBiddable == true)
			mBtnBid.setEnabled(true);
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {

		switch (id) {
		case DIALOG_BID:
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(
					R.layout.dialog_bid_entry, null);
			mBidAmount = (TextView) textEntryView
					.findViewById(R.id.amount_edit);
			return new AlertDialog.Builder(ProdDescription.this).setTitle(
					R.string.trade_place_bid).setView(textEntryView)
					.setPositiveButton(R.string.confirm,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									String price = mBidAmount.getText()
											.toString().trim();
									int bid_amount = Integer.parseInt(price);
									int bid_max_amount = Integer
											.parseInt(mResponse.mBidPrice);
									if (bid_amount <= bid_max_amount) {
										removeDialog(DIALOG_BID);
										showDialog(DIALOG_ERROR);
									} else {
										mBidPrice = price;
										Calendar cal = Calendar.getInstance();
										Date date = cal.getTime();
										SimpleDateFormat format = new SimpleDateFormat(
												"yyyy-MM-dd HH:mm:ss");
										String orderDate = format.format(date);
										String domain = getResources()
												.getString(R.string.domain);
										String query = getResources()
												.getString(
														R.string.url_prod_buy);
										String url = domain + query;
										if (AccountLogin.DEBUG)
											Log.i(TAG, "onCreateDialog url:"
													+ url);
										mCityConnection.setUrl(url);
										mCityConnection.clearParam();
										mCityConnection.AddParam("nrBidAmount",
												price);
										// ParsedLoginData.mIdUser = "1";//TO_DO
										mCityConnection.AddParam("idUser",
												ParsedLoginData.mIdUser);
										mCityConnection.AddParam(
												"idTradeProduct",
												mResponse.midTradeProduct);
										mCityConnection.AddParam(
												"dtTradeProductOrder",
												orderDate);
										mCityConnection.AddHandler(mResponse);
										mCityConnection.Execute();
										showDialog(PROGRESS_DLG);
									}
									if (AccountLogin.DEBUG)
										Log.i(TAG, "onClick price:" + price);
								}
							}).setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked cancel so do some stuff */
								}
							}).create();
		case DIALOG_ERROR:
			return new AlertDialog.Builder(ProdDescription.this).setMessage(
					"Bid price should be greater than " + mResponse.mBidPrice)
					.setPositiveButton("OK", null).create();
		case DIALOG_STATUS:
			return new AlertDialog.Builder(ProdDescription.this).setMessage(
					mResponse.mMessage).setPositiveButton("OK", null).create();
		case PROGRESS_DLG:
			ProgressDialog mDialog = new ProgressDialog(this);
			mDialog.setMessage("Request In progress....");
			mDialog.setIndeterminate(true);
			mDialog.setCancelable(true);
			return mDialog;
		default:
			return super.onCreateDialog(id, args);
		}
	}

	@Override
	public void onClick(View view) {
		if (view.getId() == R.id.trade_btn_bid) {
			showDialog(DIALOG_BID);
		}
	}

	private String CalculateElapsedTime() {
		String ItemTime = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date date = (Date) format.parse(mResponse.mBidStartTime);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage date:" + date.toString());
			long time = date.getTime();
			Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(time);
			cal.add(Calendar.HOUR, Integer.parseInt(mResponse.mItemTime));

			Date end = cal.getTime();
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage date:" + end.toString());
			Calendar cal1 = Calendar.getInstance();

			Date now = cal1.getTime();
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage now date:" + now.toString());
			long l1 = end.getTime();
			long l2 = now.getTime();
			if (end.after(now)) {
				long diff = l1 - l2;

				long secondInMillis = 1000;
				long minuteInMillis = secondInMillis * 60;
				long hourInMillis = minuteInMillis * 60;
				long dayInMillis = hourInMillis * 24;
				long yearInMillis = dayInMillis * 365;

				long elapsedYears = diff / yearInMillis;
				diff = diff % yearInMillis;
				long elapsedDays = diff / dayInMillis;
				diff = diff % dayInMillis;
				long elapsedHours = diff / hourInMillis;
				diff = diff % hourInMillis;
				long elapsedMinutes = diff / minuteInMillis;
				diff = diff % minuteInMillis;
				long elapsedSeconds = diff / secondInMillis;

				// elapsedHours += elapsedDays*24;
				if (AccountLogin.DEBUG)
					Log.i(TAG, "handleMessage elapsedYears:" + elapsedYears);
				if (AccountLogin.DEBUG)
					Log.i(TAG, "handleMessage elapsedDays:" + elapsedDays);
				if (AccountLogin.DEBUG)
					Log.i(TAG, "handleMessage elapsedHours:" + elapsedHours);
				if (AccountLogin.DEBUG)
					Log
							.i(TAG, "handleMessage elapsedMinutes:"
									+ elapsedMinutes);
				if (AccountLogin.DEBUG)
					Log
							.i(TAG, "handleMessage elapsedSeconds:"
									+ elapsedSeconds);
				ItemTime = elapsedDays + "Day " + elapsedHours + "hr "
						+ elapsedMinutes + "Mins";
				mIsBiddable = true;
				mBtnBid.setEnabled(true);
				handler.sendEmptyMessageDelayed(TIMEUPDATE, DELAY);
			} else {
				mIsBiddable = false;
				ItemTime = "0";
				mBtnBid.setEnabled(false);
				String domain = getResources().getString(R.string.domain);
				String query = getResources().getString(
						R.string.url_prod_disable);
				String url = domain + query;
				if (AccountLogin.DEBUG)
					Log.i(TAG, "CalculateElapsedTime url:" + url);
				mCityConnection.setUrl(url);
				mCityConnection.clearParam();
				if (AccountLogin.DEBUG)
					Log.i(TAG,
							"CalculateElapsedTime mResponse.midTradeProduct:"
									+ mResponse.midTradeProduct);
				mCityConnection.AddParam("idTradeProduct",
						mResponse.midTradeProduct);
				mCityConnection.AddHandler(mResponse);
				mCityConnection.Execute();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return ItemTime;
	}

	@Override
	protected void onStop() {
		super.onStop();
		handler.removeMessages(TIMEUPDATE);
	}
}
